package com.wzy.content.service.impl;

import com.wzy.content.mapper.CourseCategoryMapper;
import com.wzy.content.model.dto.CourseCategoryTreeDto;
import com.wzy.content.model.po.CourseMarket;
import com.wzy.content.service.CourseCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author wzy
 * @Date 2023/12/26 16:18
 * @description: 课程分类服务实现
 */
@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {
    @Autowired
    private CourseCategoryMapper courseCategoryMapper;
    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        //查询出的全部结果
       List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
       //将list转map，filter方法排除根节点，key是节点的id，value是CourseCategoryTreeDto对象
        Map<String, CourseCategoryTreeDto> map = courseCategoryTreeDtos.stream()
                .filter(item -> !id.equals(item.getId()))
                .collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));
        //最终返回的list
        ArrayList<CourseCategoryTreeDto> categoryTreeDtos = new ArrayList<>();

        //依次遍历每个元素，排除根节点
        courseCategoryTreeDtos.stream().filter(item->!id.equals(item.getId())).forEach(item->{
            if(item.getParentid().equals(id)){
                categoryTreeDtos.add(item);
            }
            //找到当前节点的父节点
            CourseCategoryTreeDto courseCategoryParentNode = map.get(item.getParentid());

            //将子节点放在父节点的ChildrenTreeNodes属性中
            if(courseCategoryParentNode!=null){
                if(courseCategoryParentNode.getChildrenTreeNodes()==null){
                    courseCategoryParentNode.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                }

                //下边开始往ChildrenTreeNodes属性中放子节点
                courseCategoryParentNode.getChildrenTreeNodes().add(item);
            }
        });
        return categoryTreeDtos;


    }
}
